//
//  AddShopperViewController.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/13.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit
protocol handleShoper : NSObjectProtocol {
    func handleShop(model : ShopperModelItem) -> Void
    func deleteShop(model : ShopperModelItem)->Void
}

class ShopperListViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {

    var source : Array<ShopperModelItem> = []
    weak var delegate : handleShoper?
    let table = UITableView.init(frame: CGRect.init(x: 0, y: 126 * YXHeightScale, width: YXDeviceWidth, height: YXDeviceHeight - 126 * YXHeightScale), style: .plain)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "营业员"
        self.naviHide = false
        self.defaultBackButton()
        self.view.backgroundColor = UIColor.colorWithHexString(hex: "f9f9f9")
        let button = UIButton.init(type: .system)
        button.setTitle("添加营业员", for: .normal)
        button.setTitleColor(UIColor.colorWithHexString(hex: "2c2c2c"), for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 32 * YXWidthScale)
        button.backgroundColor = UIColor.white
        button.layer.cornerRadius = YXButtonCorner
        button.layer.borderWidth = YXHeightScale
        button.layer.borderColor = UIColor.colorWithHexString(hex: "ececec").cgColor
        button.frame = CGRect.init(x: 28 * YXWidthScale, y: 18 * YXHeightScale, width: YXDeviceWidth - 56 * YXWidthScale, height: 88 * YXHeightScale)
        let img = UIImage.load(name: "icon_sales_add")?.compress(size: CGSize.init(width: 24 , height: 24 ))
        button.setImage(img, for: .normal)
        self.view.addSubview(button)
        button.tintColor = UIColor.black
        button.addTarget(self, action: #selector(addShoper), for: .touchUpInside)
        loadAndConfig()
        // Do any additional setup after loading the view.
    }
    
    @objc func addShoper() -> Void {
        let addShop = AddShopperViewController.init()
        addShop.delegate = self
        self.navigationController?.pushViewController(addShop, animated: true)
    }
    
    func loadAndConfig() -> Void {
        table.delegate = self
        table.dataSource = self
        table.register(PlainCell.classForCoder(), forCellReuseIdentifier: "plain")
        table.separatorStyle = .singleLine
        table.separatorInset = UIEdgeInsetsMake(0, 28 * YXWidthScale, 0, 0)
        table.layoutMargins = UIEdgeInsetsMake(0, 28 * YXWidthScale, 0, 0)
        table.tableFooterView = UIView.init()
        self.view.addSubview(table)
        reload()
    }
    
    //用于响应增加营业员动作
    func reload() -> Void {
        weak var sslf = self
        sslf?.beginAnim()
        Manager.shared().getShopperList(success: {(model) in
            sslf?.endAnim()
            if model.result == true {
                if let mod = model as? ShopperModel {
                    sslf?.source = mod.shoppers
                    sslf?.table.reloadData()
                }
            }else{
                sslf?.commonAlertMsg(content: model.msg)
            }
        }, fail: {(code) in
            sslf?.endAnim()
            sslf?.commonAlertMsg(content: YXNetWorkFail)
        })
    }
    
    //delegate
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return source.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        delegate?.handleShop(model: source[indexPath.row])
        let _ = self.navigationController?.popViewController(animated: true)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "plain")!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100 * YXHeightScale
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let cel = cell as! PlainCell
        cel.name = source[indexPath.row].name
        cell.separatorInset = UIEdgeInsetsMake(0, 28 * YXWidthScale, 0, 0)
        cell.layoutMargins = UIEdgeInsetsMake(0, 28 * YXWidthScale, 0, 0)
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let id = source[indexPath.row].id
        weak var sslf = self
        sslf?.beginAnim()
        Manager.shared().deleteShopper(id: String(id), success: {(model) in
            sslf?.endAnim()
            if model.result == true {
                sslf?.delegate?.deleteShop(model: sslf!.source[indexPath.row])
                sslf?.source.remove(at: indexPath.row)
                tableView.deleteRows(at: [indexPath], with: .automatic)
            }else{
                sslf?.commonAlertMsg(content: model.msg)
            }
        }, fail: {(code) in
            sslf?.endAnim()
            sslf?.commonAlertMsg(content: YXNetWorkFail)
        })
    }
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
